package com.thinkinghead.mahjongrecorder.data.connect;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.thinkinghead.mahjongrecorder.R;
import com.thinkinghead.mahjongrecorder.model.Record;
import com.thinkinghead.mahjongrecorder.model.User;
import com.thinkinghead.mahjongrecorder.ui.dialog.DialogHelper;

public class ParseAdaptor {
	private static final String TAG = "ParseAdaptor";
	private Context ctx = null;
	
	public ParseAdaptor(Context ctx){
		this.ctx = ctx;
	}
	
	public void getRecordList(RecordCallBack cb){
		getRecordListById(ParseUser.getCurrentUser(),cb);
	}
	
	public void getRecordListById(ParseUser usr,final RecordCallBack cb){
//		ParseQuery<ParseObject> query = ParseQuery.getQuery(TB_RECORD);
//		query.whereEqualTo(RECORD_CR, ParseUser.getCurrentUser());

		ParseRelation<ParseObject> relation = usr.getRelation("likes");
		ParseQuery<ParseObject> query = relation.getQuery();
		query.orderByDescending(ParseObjectConvertor.RECORD_DT);
		
		Log.d(TAG, "getRecordListById - total :"+1);
		query.findInBackground(new FindCallback<ParseObject>() {

			@Override
			public void done(List<ParseObject> pList, ParseException e) {
				List<Record> rlist = new ArrayList<Record>();
				if (e == null) {
					for (ParseObject pObj : pList) {
						Record r = new Record();
						r.setObjectID(pObj.getObjectId());
						r.setImageID(R.drawable.ic_launcher);
						r.setRecordDT(pObj.getDate(ParseObjectConvertor.RECORD_DT));
						r.setDescription(pObj.getString(ParseObjectConvertor.RECORD_RM));
						r.setNameP1(pObj.getString(ParseObjectConvertor.RECORD_P1));
						r.setNameP2(pObj.getString(ParseObjectConvertor.RECORD_P2));
						r.setNameP3(pObj.getString(ParseObjectConvertor.RECORD_P3));
						r.setNameP4(pObj.getString(ParseObjectConvertor.RECORD_P4));
						r.setCreatedBy(new User());
						rlist.add(r);
					}
				} else {
					DialogHelper.getOkAlertDialog(ctx, "Error while loading, please try again", e.getMessage());
				}
				cb.getRecordList(rlist);
			}

		});
	}
}
